package com.hc.java.pkcs.rsa;

import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

/**
 * @author : Henry
 * {@code CreateTime}: 2025-08-28 10:51
 * {@code Version}: 1.0
 */
public class SignatureDemo {
    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException {
        String a = "123";

        PublicKey publicKey = RSADemo.getPublicKey("a.pub", "RSA");
        PrivateKey privateKey = RSADemo.getPrivateKey("a.pri", "RSA");
        String signatureData = getSignature(a, "SHA256withRSA", privateKey);
        System.out.println("签名：" + signatureData);

        // 校验签名
        boolean b = verifySignature(a, "SHA256withRSA", publicKey, signatureData);
        System.out.println("校验结果：" + b);
    }

    /**
     * 校验签名
     *
     * @param input         原文
     * @param algorithm     算法
     * @param publicKey     公钥
     * @param signatureData 签名密文
     * @return 结果
     */
    private static boolean verifySignature(String input, String algorithm, PublicKey publicKey, String signatureData) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        // 获取签名对象
        Signature signature = Signature.getInstance(algorithm);
        // 初始化校验
        signature.initVerify(publicKey);
        // 传入原文
        signature.update(input.getBytes());
        // 开始校验
        return signature.verify(Base64.getDecoder().decode(signatureData));
    }

    /**
     * 生成数字签名
     *
     * @param input      原文
     * @param algorithm  算法
     * @param privateKey 私钥
     * @return 签名
     */
    private static String getSignature(String input, String algorithm, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        // 获取签名对象
        Signature signature = Signature.getInstance(algorithm);
        // 初始化签名
        signature.initSign(privateKey);
        // 传入原文
        signature.update(input.getBytes());
        // 开始签名
        byte[] sign = signature.sign();
        return Base64.getEncoder().encodeToString(sign);
    }
}
